package com.learn.motion.ui

import android.os.Build
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.Toolbar
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import com.google.android.material.appbar.AppBarLayout
import com.learn.motion.R

object EdgeToEdge : EdgeToEdgeImpl by if (Build.VERSION.SDK_INT >= 21) {
    EdgeToEdgeApi21()
} else {
    EdgeToEdgeBase()
}

private interface EdgeToEdgeImpl {
    /**
     * 配置应用栏和工具栏以实现边缘到边缘显示。
     *
     * @param appBar [AppBarLayout]
     * @param toolbar 在[AppBarLayout]中的[Toolbar]
     */
    fun setUpAppBar(appBar: AppBarLayout, toolbar: Toolbar) {

    }

    /**
     * 为滚动试图配置边缘到边缘显示
     *
     * @param scrollingContent 一个滚动视图，可以是一个RecyclerView或ScrollView
     */
    fun setUpScrollingContent(scrollingContent: ViewGroup) {}
}

private class EdgeToEdgeBase : EdgeToEdgeImpl

@RequiresApi(21)
private class EdgeToEdgeApi21 : EdgeToEdgeImpl {
    override fun setUpAppBar(appBar: AppBarLayout, toolbar: Toolbar) {
        val toolbarPadding = toolbar.resources.getDimensionPixelSize(R.dimen.spacing_medium)
        ViewCompat.setOnApplyWindowInsetsListener(appBar) { _, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            appBar.updatePadding(top = systemBars.top)
            toolbar.updatePadding(
                left = toolbarPadding + systemBars.left,
                right = systemBars.right
            )
            insets
        }
    }

    override fun setUpScrollingContent(scrollingContent: ViewGroup) {
        val originalPaddingLeft = scrollingContent.paddingLeft
        val originalPaddingRight = scrollingContent.paddingRight
        val originalPaddingBottom = scrollingContent.paddingBottom

        ViewCompat.setOnApplyWindowInsetsListener(scrollingContent) { _, windwoInset ->
            val systemBars = windwoInset.getInsets(WindowInsetsCompat.Type.systemBars())
            scrollingContent.updatePadding(
                left = systemBars.left + originalPaddingLeft,
                right = systemBars.right + originalPaddingRight,
                bottom = systemBars.bottom + originalPaddingBottom
            )
            windwoInset
        }
    }
}